package com.yz.xyt.service.impl;

import com.yz.xyt.domain.Post;
import com.yz.xyt.domain.Staff;
import com.yz.xyt.mapper.PostMapper;
import com.yz.xyt.service.IPostService;
import com.yz.xyt.utils.DateUtils;
import com.yz.xyt.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PostServiceImpl implements IPostService {

    @Autowired
    PostMapper postMapper;

    @Override
    public int deleteByPrimaryKey(Integer pid) {
        return postMapper.deleteByPrimaryKey(pid);
    }

    @Override
    public int insert(Post record) {
        return postMapper.insert(record);
    }

    @Override
    public int insertSelective(Post record) {
        return postMapper.insertSelective(record);
    }

    @Override
    public Post selectByPrimaryKey(Integer pid) {
        return postMapper.selectByPrimaryKey(pid);
    }

    @Override
    public int updateByPrimaryKeySelective(Post record) {
        return postMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Post record) {
        return postMapper.updateByPrimaryKey(record);
    }

    @Override
    public Post findByPostNumber(String postNumber) {
        return postMapper.findByPostNumber(postNumber);
    }

    @Override
    public int updateByPostNumberSelective(Post post) {
        return postMapper.updateByPostNumberSelective(post);
    }

    @Override
    public int deleteByPostNumber(String postNumber) {
        return postMapper.deleteByPostNumber(postNumber);
    }

    @Transactional
    @Override
    public void syncAddPost(List<Post> list) {
        //过滤重复数据
        List<Post> postList = new ArrayList<>();
        list.stream().forEach(post -> {
            Post record = findByPostNumber(post.getPostNumber());
            if(record == null){
                postList.add(post);
            }
        });

        //新增岗位
        postList.stream().peek(post -> {
            post.setCreateBy(SecurityUtils.getUsername());
            post.setCreateDate(DateUtils.getNowDate());
        }).collect(Collectors.toList()).stream().forEach(this::insert);


    }

    @Transactional
    @Override
    public void syncUpdatePost(List<Post> list) {
        //更新岗位信息
        list.stream().peek(post -> {
            post.setUpdateBy(SecurityUtils.getUsername());
            post.setUpdateDate(DateUtils.getNowDate());
        }).collect(Collectors.toList()).forEach(this::updateByPostNumberSelective);

    }

    @Transactional
    @Override
    public void syncDeletePost(List<Post> list) {
        list.stream().forEach(post -> {
            postMapper.deleteByPostNumber(post.getPostNumber());
        });
    }
}
